﻿using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;

namespace geopg_wp7
{
    public partial class InfoPage : PhoneApplicationPage
    {
        public InfoPage()
        {
            InitializeComponent();
            textBlock1.Text = "Total Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceTotalMemory"));
            textBlock2.Text = "Used Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"));
            textBlock3.Text = "Peak Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage"));
            getSessionData();
        }

        private void login_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LoginPage.xaml", UriKind.Relative));
        }

        private void mainPage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
        }

        private void localPictures_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LocalPicturesPage.xaml", UriKind.Relative));
        }

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//SettingsPage.xaml", UriKind.Relative));
        }

        private void info_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//InfoPage.xaml", UriKind.Relative));
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBlock1.Text = "Total Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceTotalMemory"));
            textBlock2.Text = "Used Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"));
            textBlock3.Text = "Peak Mem: " + ConvertToMB((long)Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage"));
            getSessionData();
        }

        public string ConvertToMB(long bytes)
        {
            return ((bytes / 1024f) / 1024f).ToString("0.00") + " MByte";
        }

        void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            // Dispatcher fixes SystemAuthorizationException for string postData
            this.Dispatcher.BeginInvoke(delegate()
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                /*System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
                // Input-String for LogOut unknown yet
                string postData = "user=WP7";
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();*/
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            });
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;
                response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                System.IO.Stream streamResponse = response.GetResponseStream();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(streamResponse);
                string responseString = streamReader.ReadToEnd();
                Console.WriteLine(responseString);
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Output is the position of the string. If it doesn't exist, its position is "-1"
                    if (responseString.IndexOf("cause") != -1)
                    {
                        if (responseString.IndexOf("cause=\"0\"") != -1)
                            MessageBox.Show("Internal Error (SQL)");
                        else if (responseString.IndexOf("cause=\"1\"") != -1)
                            MessageBox.Show("Expected POST but got GET request.");
                        else if (responseString.IndexOf("cause=\"3\"") != -1)
                            MessageBox.Show("You were not logged in. No session data available.");
                        else if (responseString.IndexOf("cause=\"4\"") != -1)
                            MessageBox.Show("Not enough privileges to perform action.");
                        else
                            MessageBox.Show("Unexpected Error");
                        // More Error-Codes to be done!
                    }
                    else
                    {
                        MessageBox.Show(responseString);
                    }
                });
                streamResponse.Close();
                streamReader.Close();
                response.Close();
            }
            catch (WebException e)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    MessageBox.Show("Can't establish connection.");
                });
            }
        }

        void getSessionData()
        {
            Uri address = new Uri("http://geopg.de/backend/UserSessionData");
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Headers["Cookie"] = GlobalVariables.cookie;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
        }
    }
}